package com.zjl.SpringBoot.第11章_远程调用;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import reactor.core.publisher.Mono;

/**
 * Spring 6新功能
 *
 * Spring允许我们通过定义接口的方式，给任意位置发送http请求,实现远程调用，可以用来简化
 * HTTP远程访问。
 * 需要 webflux 场景可
 */
@SpringBootTest
public class B2_远程调用 {

    @Test//访问外部接口方式1
    public void HTTP01(){
        //创建客户端
        WebClient build = WebClient.builder()
                .baseUrl("http://127.0.0.1:7777/")//可以定义访问 ip  这样  接口就不用输入 很长了
                .codecs(c -> {c.defaultCodecs().maxInMemorySize(256 * 1024 * 1024);})
                .build();

        //创建工厂
        HttpServiceProxyFactory build1 = HttpServiceProxyFactory.builderFor(WebClientAdapter.create(build)).build();

        //获取代理对象
        B2_HTTP_Interface远程调用 client = build1.createClient(B2_HTTP_Interface远程调用.class);
        //访问
        Mono<String> search = client.search(1L);

        System.out.println(search.block());//返回值
    }

    @Autowired
    B2_HTTP_Interface远程调用 b2;

    @Test//访问外部接口方式2
    public void HTTP02(){
        //访问
        Mono<String> search = b2.search2(2L);//
        System.out.println(search.block());//返回值
    }
    @Autowired
    HttpServiceProxyFactory httpServiceProxyFactory;
    @Test//访问外部接口方式3
    public void HTTP03(){
        //访问
        B2_HTTP_Interface远程调用 client = httpServiceProxyFactory.createClient(B2_HTTP_Interface远程调用.class);
        Mono<String> search = client.search2(3L);//
        System.out.println(search.block());//返回值
    }

}
@Configuration
class B2Config {
    @Bean
    public HttpServiceProxyFactory httpServiceProxyFactory(){
        //创建客户端
        WebClient webClient = WebClient.builder()
//                .baseUrl("http://127.0.0.1:7777/")//不写 就要长路径
                .codecs(c -> {c.defaultCodecs().maxInMemorySize(256 * 1024 * 1024);})
                .build();

        //创建工厂
        HttpServiceProxyFactory build = HttpServiceProxyFactory.builderFor(WebClientAdapter.create(webClient)).build();

        return build;
    }

    @Bean
    public B2_HTTP_Interface远程调用 b2(){
        HttpServiceProxyFactory httpServiceProxyFactory = httpServiceProxyFactory();
        //获取代理对象
        B2_HTTP_Interface远程调用 client = httpServiceProxyFactory.createClient(B2_HTTP_Interface远程调用.class);
        return client;
    }
}
